package com.tang.service;

import com.tang.dao.SysGeneratorDao;
import com.tang.utils.GenUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 *
 * @author tangyifei
 * @email 15062230055@163.com
 * @date 2018年12月19日 下午3:33:38
 */
@Service
public class SysGeneratorService {

    @Resource
    private SysGeneratorDao sysGeneratorDao;

    public List<Map<String, Object>> queryList(Map<String, Object> map) {
        return sysGeneratorDao.queryList(map);
    }

    public int queryTotal(Map<String, Object> map) {
        return sysGeneratorDao.queryTotal(map);
    }

    public Map<String, String> queryTable(String tableName) {
        return sysGeneratorDao.queryTable(tableName);
    }

    public List<Map<String, String>> queryColumns(String tableName) {
        return sysGeneratorDao.queryColumns(tableName);
    }

    public byte[] generatorCode(String[] tableNames, String moduleName, String packageName, String mainPath, String tablePrefix, String modulePrefix ) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for(String tableName : tableNames) {
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            Map<String, Object> map = new HashMap<>();
            map.put("table", table);
            map.put("columns", columns);
            map.put("zip", zip);
            map.put("moduleName", moduleName);
            map.put("packageName", packageName);
            map.put("mainPath", mainPath);
            map.put("tablePrefix", tablePrefix);
            map.put("modulePrefix", modulePrefix );
            //生成代码
            GenUtils.generatorCode(map);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
}
